allDevices=("dev-esp32" "dev-esp32s3" "prod-esp32N8R2" "dev-wrov1")
allTargets=("esp32" "esp32s3" "esp32" "esp32")
echo "Building z-way-esp firmware for all Z-Way-ESP boards variants"
BUILD_DIR=$1

export IDF_PYTHON_ENV_PATH=~/.espressif/python_env/idf5.3_py3.8_env
export IDF_TOOLS_PATH=~/.espressif
export IDF_PATH=~/esp/v5.3.1/esp-idf
export PYTHON=~/.espressif/python_env/idf5.3_py3.8_env/bin/python
CORE_DUMP_TOOL=${IDF_PATH}/components/partition_table
PARTITION_TABLE_TOOL=${IDF_PATH}/components/partition_table
EXTENSA_ELF_TOOLS=${IDF_TOOLS_PATH}/tools/xtensa-esp-elf/esp-13.2.0_20240530/xtensa-esp-elf/bin
EXTENSA_PYTHON_ENV=${IDF_PYTHON_ENV_PATH}/bin:
ESP_ROMS=${IDF_TOOLS_PATH}/tools/esp-rom-elfs/20240305

export PATH=$PATH:$CORE_DUMP_TOOL:$PARTITION_TABLE_TOOL:$EXTENSA_ELF_TOOLS:$EXTENSA_PYTHON_ENV:$ESP_ROMS
echo "PATH:$PATH"
# IDF_PYTHON=$1
# IDF_CMD=$2

CURRENT_DIR=$(pwd)

echo "---using BUILDDIR:${BUILD_DIR} IDF_PATH:${IDF_PATH} PATH:${PATH}"

function die {
	echo "FAILED to build $1"
	exit -1
} 

for i in ${!allDevices[@]}; do
  device=${allDevices[$i]}
  targ=${allTargets[$i]}
  echo "Building firmware for '$device' target:$targ"
  echo "--- Clean ---"
  rm ${CURRENT_DIR}/sdkconfig
  rm -r ${BUILD_DIR}
  mkdir -p ${BUILD_DIR}/bin_arch
  echo "--- Set target ---"
  cmake -S ${CURRENT_DIR} -B ${BUILD_DIR} -D DEVICE=$device -D IDF_TARGET=$targ -D ESP_PLATFORM=1 -G Ninja || die $device
  cd ${BUILD_DIR}
  #ninja set-target  $targ
  ninja || die $device
  echo "--- Creating binaries archive ---"
  cp  ./bootloader/bootloader.bin ./bin_arch/
  cp  ./partition_table/partition-table.bin ./bin_arch/
  cp  ./z-way-esp32.bin ./bin_arch/
  zip -r "${CURRENT_DIR}/bin/z-way-$device.zip" ./bin_arch
  cd ${CURRENT_DIR}
  echo "--- Done ---"
done